package com.up.upzl.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.up.upzl.base.service.impl.BaseServiceImpl;
import com.up.upzl.biz.domain.Customer;
import com.up.upzl.biz.domain.Customer.EntrustType;
import com.up.upzl.biz.repository.CustomerRepository;
import com.up.upzl.biz.service.CustomerService;

import utils.UpzlUtils;

@Service
public class CustomerServiceImpl extends BaseServiceImpl<Customer, Long> implements CustomerService {

	@Autowired
	private CustomerRepository customerRepository;

	@Override
	public Page<Customer> findByCondition(String account,Date beginTime, Date endTime, Pageable page) {

		return customerRepository.findAll(new Specification<Customer>() {
			public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(account))
					predicates.add(cb.and(cb.like(root.get("account"), "%" + account + "%")));
				if (beginTime != null) {
					predicates.add(cb.and(cb.greaterThanOrEqualTo(root.get("createTime"), beginTime)));
				}
				if (endTime != null) {
					predicates.add(cb.and(cb.lessThanOrEqualTo(root.get("createTime"), UpzlUtils.timeHelper(endTime))));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}
	
	@Override
	public Page<Customer> findByCondition(String account,EntrustType entrustType,Date beginTime, Date endTime, Pageable page) {

		return customerRepository.findAll(new Specification<Customer>() {
			public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(account))
					predicates.add(cb.and(cb.like(root.get("account"), "%" + account + "%")));
				if (beginTime != null) {
					predicates.add(cb.and(cb.greaterThanOrEqualTo(root.get("createTime"), beginTime)));
				}
				if (endTime != null) {
					predicates.add(cb.and(cb.lessThanOrEqualTo(root.get("createTime"), UpzlUtils.timeHelper(endTime))));
				}
				if (entrustType !=null) {
					predicates.add(cb.and(cb.equal(root.get("entrustType"), entrustType)));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}
}
